/**
 * 全站权限配置
 *
 */
import router from './router/router'
import store from './store'
import { validatenull } from '@/util/validate'
import { getToken, setToken } from '@/util/auth' // getTokenConfigObj
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import website from '@/config/website'
// import { removeTokenConfig } from '@/util/auth'

NProgress.configure({ showSpinner: false })

/**
  * 页面跳转检查
  * @param {*} to
  * @param {*} next
  * @returns
  */
const checkNext = (to, next) => {
  // 统一身份认证回调页面
  if (to.path === '/back' || to.path === '/tokenConfig') {
    next()
    return false
  }
  // if (!checkTokenConfig(to, next)) {
  //   return false
  // }
  const meta = to.meta || {}

  // if (to.path === '/login') {
  //   next()
  //   return false
  // }
  // const tokenData = getTokenConfigObj().tokenData
  // // 如果是普通登录模式或逃生通道
  // if (process.env.VUE_APP_TYPE === 'boot' || (tokenData && tokenData.sosWay)) {
  //   if (to.path === '/login') {
  //     next()
  //     return false
  //   }
  // }
  // 不需要鉴权的页面
  if (meta.isAuth === false) {
    next()
    return false
  }

  return true
}
/**
  * 保存当前url，用于登录后跳转页面
  * @param {*} to
  */
// eslint-disable-next-line no-unused-vars
const saveCurrentUrl = to => {
  const meta = to.meta || {}
  if (meta.isAuth !== false && to.path !== '/tokenConfig' && to.path !== '/back') {
    // 回调地址带#无法解析
    sessionStorage.setItem(website.key + '-token-config' + '-beforeTokenConfigUrl', to.fullPath)
  }
}
/**
  * 检查是否已经有tokenConfig信息，如果没有则跳转tokenConfig页面
  */
// const checkTokenConfig = (to, next) => {
//   const tokenConfig = getTokenConfigObj()
//   if (!tokenConfig || !Object.keys(tokenConfig).length) {
//     if (to.path === '/tokenConfig') {
//       next()
//       return false
//     }
//     const meta = to.meta || {}
//     next({ path: '/tokenConfig', query: { isAuth: meta.isAuth, path: to.path }})
//     return false
//   }
//   return true
// }

const addTag = to => {
  const value = to.query.src || to.path
  const label = to.query.name || to.name
  const meta = to.meta || router.$avueRouter.meta || {}
  const i18n = to.query.i18n
  if (meta.isTab !== false && !validatenull(value) && !validatenull(label)) {
    store.commit('ADD_TAG', {
      label: label,
      value: value,
      params: to.params,
      query: to.query,
      meta: (() => {
        if (!i18n) {
          return meta
        }
        return {
          i18n: i18n
        }
      })(),
      group: router.$avueRouter.group || []
    })
  }
}

router.beforeEach((to, from, next) => {
  // start progress bar
  const fromFirstRouteName = from.path.split('/')[1]
  const toFirstRouteName = to.path.split('/')[1]
  // 二级路由内跳转
  if (fromFirstRouteName === toFirstRouteName) {
    // 判断来源路由是否是侧边栏
    // if (to.meta.isSideBar) {
    //   store.commit('REMOVE_ALL_PAGE')
    // }
    if (from.meta.originAlive && from.meta.from && from.meta.from.includes(to.name)) {
      store.commit('ADD_THE_PAGE', from.meta.pageName)
    } else if (to.meta.originAlive && to.meta.isSideBar) { // 当侧边栏二级路由之间跳转时，应对跳转后的路由添加缓存
      store.commit('REMOVE_ALL_PAGE')
      store.commit('ADD_THE_PAGE', 'Index')
      store.commit('ADD_THE_PAGE', to.meta.pageName)
    } else {
      NProgress.start()
      // store.commit('REMOVE_ALL_PAGE')
      store.commit('REMOVE_THE_PAGE', 'Index')
      store.commit('REMOVE_THE_PAGE', from.meta.pageName)
    }
    if (to.meta.isSideBar && from.meta.originAlive) {
      store.commit('REMOVE_THE_PAGE', from.meta.pageName)
    }
  } else { // 当路由在一级路由之间跳转时
    // 如果当前为路由页时，清空所有页面缓存
    if (to.meta.isSideBar && !to.meta.originAlive) {
      store.commit('REMOVE_ALL_PAGE')
    } else if (to.meta.isSideBar && from.meta.originAlive) {
      store.commit('REMOVE_THE_PAGE', from.meta.pageName)
    }

    if (to.meta.isSideBar && to.meta.originAlive) {
      store.commit('ADD_THE_PAGE', 'Index')
      store.commit('ADD_THE_PAGE', to.meta.pageName)
    }
  }
  NProgress.start()
  const { token } = to.query
  if (token) {
    setToken(token)
  }

  if (getToken()) {
    const lockPage = store.getters.website.lockPage // 锁屏页
    if (store.getters.isLock && to.path !== lockPage) { // 如果系统激活锁屏，全部跳转到锁屏页
      next({ path: lockPage })
    } else if (to.path === '/login') { // 如果登录成功访问登录页跳转到主页
      next({ path: '/' })
    } else {
      addTag(to)
      next()
    }
  } else {
    saveCurrentUrl(to)

    if (!checkNext(to, next)) {
      return
    }
    // 没登录，重新获取tokenConfig
    // removeTokenConfig()
    next({ path: '/login', query: { isAuth: to.meta.isAuth, path: to.path }})
    // const callBackUrl = window.location.protocol + '//' + window.location.host + '/back'
    // window.location.replace(process.env.VUE_APP_HOME_LOGIN + '?back=' + callBackUrl || '')
  }
})

router.afterEach(() => {
  NProgress.done()
  let title = store.getters.tag.label
  const i18n = store.getters.tag.meta.i18n
  title = router.$avueRouter.generateTitle(title, i18n)
  // 根据当前的标签获取label的值动态设置浏览器标题
  router.$avueRouter.setTitle(title)
})
